package com.itheima.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * JDBC工具类
 * @author Unicorn
 * @version v1.0
 * @createTime 2019年2月24日 下午7:08:01
 *
 */
public class JDBCUtils2 {

	// 获得c3p0连接池对象
	private static final ComboPooledDataSource DATA_SOURCE = new ComboPooledDataSource();
	private static final ThreadLocal<Connection> tl = new ThreadLocal<>();
	/**
	 * 获得数据库连接对象
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = tl.get();
			if (conn == null) {
				conn = DATA_SOURCE.getConnection();
				tl.set(conn);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void beginTransaction() throws SQLException {
		Connection conn = null;
		conn = tl.get();
		if (conn == null) {
			conn = DATA_SOURCE.getConnection();
			tl.set(conn);
		}
		conn.setAutoCommit(false);
	}
	
	public static void commitTransaction() throws SQLException {
		Connection conn = tl.get();
		conn.commit();
	}
	
	public static void rollBackTransaction() throws SQLException {
		Connection conn = tl.get();
		conn.rollback();
	}
	
	/**
	 * 获得c3p0连接池对象
	 * @return
	 */
	public static DataSource getDataSource() {
		return DATA_SOURCE;
	}
}
